/**
 * @description menubutton组件
 */
 
(function(MenuButton){
	// set defalut config
	var config = {
		panelBegin : "<ul>",
		item : 	'<li class="ccay-menubutton-item ${itemCSS}" ${attr}><a class="ccay-icon ${icon}"></a><span>${text}</span></li>', 
		panelEnd : "</ul>",
		defaultItemClass : 'defautl-item', // 默认项的按钮样式
		css : {top : -1,left:5}
	};
	
	//define control flow
	var flow = {
		init:function(menuButton,op){
			if(menuButton.dom.hasClass("init")){
				op._init = true;
				return;
			}
			// 外围div
		   	menuButton.dom.addClass("ccay-menubutton");
		   	//增加外围div的两个属性配置.ccayPermission:权限列表; uClass:用户增加自定义的class
			if(op.ccayPermission){
				menuButton.dom.attr("ccayPermission",op.ccayPermission);
			}
			if(op.uClass){
				menuButton.dom.addClass(op.uClass);
			}
		   	// 内生成button
		    menuButton.dom.append("<div class='ccay-menubutton-body'></div>")
		},
		build:function(menuButton,op){
			var selector = "";
			if(op._init){
				selector = menuButton.dom.children(".ccay-menubutton-selector");
			}else{
				selector = $.create('div').addClass('ccay-menubutton-selector');
			}
			// 是否自定义样式
			op.selectorClass && selector.addClass(op.selectorClass);
			// 生成默认菜单
			helper.buildDefaultMenu(selector, menuButton, op);
			// 生成下拉框
			helper.buildSelector(selector, menuButton, op);
			// 设置下拉按钮
			helper.buildTrigger(menuButton, op);
		}
	};
	
	//define control manager
	var manager = {
		// 得到菜单列表
		getMenuItemList:function(){
			return helper.getSelector(this).children("ul").children();
		},
		// 得到菜单项的数目
		getMenuItemCount:function(){
			return this.op.itemCount;
		},
		// 添加菜单项
		addMenuItem : function(itemOp){ // 单个添加
			if(itemOp.permission && Ccay.Permission.check(itemOp.permission) === false){
				return;
			};
			var body = helper.getSelector(this).children();
			// 用户属性处理
			itemOp.attr = helper.attrConvert(itemOp.attr) || "";
			itemOp.itemCSS = itemOp.itemCSS || "";
			// 生成dom
			body.append(Ccay.UI.tmplList(this.op.item, [itemOp]));
			// 绑定事件
			var lastListItem = body.children(":last");
			helper.setItemEvent(lastListItem,itemOp.click);
			this.op.itemCount++;
		},
		// 移除菜单项
		removeMenuItem : function(id){
			var body = helper.getSelector(this).children();
			body.children("#"+id).remove();
		},
		// 禁用
		disabled : function(flag){
			if(flag){
				this.dom.children().attr("disabled","disabled").addClass("disabled")
			}else{
				this.dom.children().removeAttr("disabled").removeClass("disabled")
			}
		}
	};
	
	//define inner functions
	var helper = {
		// 系统生成id的变量
		index : 0,
		// 弹出菜单框
		popup : function(menu, op, selector){
			// 宽度匹配
			var sumBtnWidth = menu.dom.width();
			if(selector.width() < sumBtnWidth){
				selector.width(sumBtnWidth);
			};
			var position = {};
			$.extend(position, op.css);
			position.top = (position.top || 0) + menu.dom.outerHeight();
			Ccay.UI.popup(menu.dom, selector, position);
		},
		// 设置默认菜单
		buildDefaultMenu:function(selector, menuButton, op){
			if(op._init){
				// 若一级菜单无事件绑定，则打开下拉
				var body = menuButton.dom.children(".ccay-menubutton-body");
				if(!body.attr("onclick")){
					body.click(function(){
					  $(this).next(".ccay-menubutton-btn").click();
					})
				}
				return;
			}
			var hasDafaultMenu = false;
			// 生成一级按钮
			if(op.defaultImg){
				menuButton.dom.children().append($("<a class='ccay-icon "+op.defaultImg+"'></a>")); 
			}
			menuButton.dom.children().append($i18n(op.defaultText));
			// 判断是否设置默认菜单  
			for(var i = 0 ; i < op.menus.length ; i++){
				if(op.menus[i].isDefaultMenu == true ){
					//根据指定默认按钮及其权限点控制按钮事件
					if(op.menus[i].permission && Ccay.Permission.check(op.menus[i].permission)){
						hasDafaultMenu = op.menus[i].click;
					    break;
					}
				}
			}
			// 设置默认事件
			if(op.defaultEvent){ // 默认事件优先级最高
				this.setItemEvent(menuButton.dom.children(".ccay-menubutton-body"), op.defaultEvent);
			};
			// 设置默认菜单
			if( !op.defaultEvent && hasDafaultMenu){
				this.setItemEvent(menuButton.dom.children(".ccay-menubutton-body"), hasDafaultMenu);
			};
			// 无设置默认事件和默认菜单时，点击打开下拉列表
			if(!op.defaultEvent && !hasDafaultMenu){
				//this.popupEvent(menuButton.dom.children(".ccay-menubutton-body"), selector, menuButton, op);
				// 绑定点击下拉按钮
				menuButton.dom.children(".ccay-menubutton-body").click(function(){
				  $(this).next(".ccay-menubutton-btn").click();
				})
			}
		},
		popupEvent:function(dom, selector, menuButton, op){
			dom.click(function(){
					     this.focus();
					     if(!selector.is(":hidden")){
					     	selector.hide();
					     } else {
				        	helper.popup(menuButton, op, selector)
				    	 }
				    	 return false;
			}).blur(function(e){
				setTimeout(function(){
					if(!$(e.target).is(":focus")){
						if(!selector.data("inpopup")){
							selector.hide();
							selector.data("inpopup",false);
						}
					}
				},150);
			});
			//lwx200947 修复长时间按钮下拉按钮，按钮消失问题
			selector.mousedown(function(){
				selector.data("inpopup",true);
			})
			selector.click(function(){
				setTimeout(function(){
					selector.hide();
					selector.data("inpopup",false);
				},150);
			})
		},
		// 设置下拉按钮
		buildTrigger : function(menu, op){
			var trigger = "",selector = "";
			if(op._init){
				trigger = menu.dom.children('.ccay-menubutton-btn');
				selector = menu.dom.children('.ccay-menubutton-selector');
			}else{
				// tabIndex使其可有焦点
				trigger = $.create('a', 'ccay-menubutton-btn').attr("tabIndex", "-1");
				trigger.insertAfter(menu.dom.children(".ccay-menubutton-body"));
				selector = helper.getSelector(menu);
			}
			this.popupEvent(trigger,selector,menu,op);
		},
		// 生成下拉区
		buildSelector : function(selector, menuButton, op){
			if(op._init){
				op.itemCount = this.getSelector(menuButton).children().length;
				return;
			}
			var dom = menuButton.dom,
				id = dom.id();
			if (!id){
				id = 'menu_button_' + (this.index++);
				dom.id(id);
			};
			id += '_menulist';
			selector.id(id).data('op', op);
			op.selectorId = id ;
			var menu = this;
			for(var i = 0 ; i < op.menus.length ; i++){
				op.menus[i].text = $i18n(op.menus[i].text || "");
				// id设置处理
       	    	if(op.menus[i].id){
       	    		if(op.menus[i].attr)
						op.menus[i].attr.id = op.menus[i].id;
					else
						op.menus[i].attr = {id:op.menus[i].id};
       	    	};
				// 项按钮样式
				op.menus[i].icon = op.menus[i].icon || "";
				// 自定义项样式
				op.menus[i].itemCSS = op.menus[i].itemCSS || "";
				// 用户属性处理
				op.menus[i].attr = op.menus[i].attr && this.attrConvert(op.menus[i].attr) || "";
			};
			selector.append(op.panelBegin + Ccay.UI.tmplList(op.item, op.menus) + op.panelEnd);
			selector.appendTo(dom);
			// 绑定事件
			op.itemCount = 0;
			selector.find(".ccay-menubutton-item").each(function(i){
				   var me = $(this);
				   // 去除空id属性
				   if(!me.id()){
				   	 me.removeAttr("id");
				   };
				   if (op.menus[i].permission){
						if (Ccay.Permission.check(op.menus[i].permission)){
							op.itemCount++;
							if (!op.defaultEvent && op.menus[i].isDefaultMenu){
								me.addClass(op.defaultItemClass);
							};
							menu.setItemEvent(me,op.menus[i].click);
						}else{
							me.remove();
						}
					}else{
						op.itemCount++;
						if (!op.defaultEvent && op.menus[i].isDefaultMenu){
							me.addClass(op.defaultItemClass);
						};
						menu.setItemEvent(me, op.menus[i].click);
				    };
			});
		},
		// 根据selectorId获取selector
		getSelector:function(menu){
			if(menu.op._init){
				return $(".ccay-menubutton-selector", menu.dom);
			}
			return $("#"+menu.op.selectorId, menu.dom);
		},
		// 事件设置
		setItemEvent : function(dom, event){
			if (typeof event == "string") {
				dom.attr("onclick", event)
			} else {
				dom.click(event);
			}
		},
		// 用户自定义属性处理
		attrConvert : function(attrJson) {
			if (attrJson) {
				var attr = [];
				for (var k in attrJson) {
					attr.push(k + "=\"" + attrJson[k] + "\"")
				}
				return attr.join(" ");
			} else {
				return "";
			};
		}
	};
	
	//create XControl
	var XMenuButton = Ccay.UI.XControl("XMenuButton", flow, config, manager);
	
	// create jquery plugin
	$.fn.ccayMenuButton = function(op){
		if(this.length == 0){
		   return;
		}else{
			return this.each(function(){
				new XMenuButton($(this), op);
			})
		}
	};
	
})(Ccay.UI.XMenuButton);

